package com.xhh.nphm.web.controller.system;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.xhh.nphm.common.core.controller.BaseController;
import com.xhh.nphm.common.core.domain.AjaxResult;
import com.xhh.nphm.common.core.domain.entity.SysUser;
import com.xhh.nphm.common.core.domain.entity.annotation.MultiRequestBody;
import com.xhh.nphm.common.utils.BaiduApiUtils;
import com.xhh.nphm.system.domain.BSort;
import com.xhh.nphm.system.service.ICommonService;
import com.xhh.nphm.system.service.impl.CommonServiceImpl;
import com.xhh.nphm.system.vo.AiAnsweringVO;
import com.xhh.nphm.web.AuthUtil;
import io.swagger.v3.oas.annotations.parameters.RequestBody;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import org.aspectj.weaver.loadtime.Aj;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.*;

import static com.xhh.nphm.AuthUtil.builderHeader;

/**
 * 百度接口
 */
@RestController
@RequestMapping("/api/bd")
public class BaiduApiController extends BaseController {
    @Value("${baiduUrl}")
    private String baseUrl;

    @Value("${pd.assigndept}")
    private String assigndeptUrl;

    @Autowired
    private BaiduApiUtils baiduApi;

    @Autowired
    private CommonServiceImpl commonServiceImpl;

    @Autowired
    private ICommonService commonService;

    private final String prefix = "system/mTelRcd/cmnFile";

    /**
     * 地图地址推荐
     *
     * @param address
     * @param city
     * @return
     */
    @GetMapping("/search")
    public String post(String address, String city) {
        // 地图地址推荐
//        String url = baseUrl+"/openapi/v1/event/analysis/part1/dugis/search?address=" + address + "&city=" + city;
        String url = "http://10.1.227.188:8752/v1/dugis/search?address="+address+"&city="+city;
        return getCommon(url);
    }

    /**
     * 关键词搜索
     * 
     * @param address 注意letter是一个json字符串 例如{\"letter\":\"12345\"}
     * @return
     */
    @PostMapping("letter")
    public String letter(@MultiRequestBody String address) {
        // 关键词搜索
//        String url = baseUrl+"/openapi/yuqing/icp/hotquery/letterHot";
        String url = "http://10.1.227.188:8752/letterHot";
        return postCommon(address, url);
    }

    /**
     * 工单分类
     *
     * @param workorder 注意参数一个json对象字符串
     * @return
     */
    @PostMapping("workorder")
    public String workorder(@MultiRequestBody String workorder) {
        // 工单分类
//        String url = baseUrl+"/openapi/v1/event/analysis/part1/chengdu/tag";
        String url = "http://10.1.227.188:8752/v1/chengdu/tag";
        return postCommon(workorder, url);
    }

    /**
     * 智能匹配部门
     *2023/4/23
     * @param
     * @return
     */
    @PostMapping("assigndept")
    public  List<Map<String, Object>> assigndept(String content,String sort) {
        Map<String, Object> map=new HashMap<>();
        map.put("content",content);
        map.put("sort",sort);
//        String url = "http://222.210.127.166:8282/api/pd/assigndept";
        String url = assigndeptUrl;
        // 1. 声明httppost
        HttpPost httpPost = new HttpPost(url);
        // 2.封装请求参数
        // 声明封装表单数据的容器
        List<NameValuePair> parameters = new ArrayList<NameValuePair>(0);
        if (map != null) {
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                // 封装请求参数到容器中
                parameters.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
            }
        }
        // 创建表单的Entity类
        UrlEncodedFormEntity entity = null;
        try {
            entity = new UrlEncodedFormEntity(parameters, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        // 3. 把封装好的表单实体对象设置到HttpPost中
        httpPost.setEntity(entity);
        // 4. 使用Httpclient发起请求
        CloseableHttpResponse response = null;
        try {
            response = HttpClients.createDefault().execute(httpPost);
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 响应体内容
        String body = null;
        if (response.getEntity() != null) {
            try {
                body = EntityUtils.toString(response.getEntity(), "UTF-8");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        JSONObject obj=JSONObject.parseObject(body);
        JSONArray arr = obj.getJSONArray("data");
        String js=JSON.toJSONString(arr, SerializerFeature.WriteClassName);
        List<Map<String, Object>> list = JSON.parseObject(js, List.class);
        return list;
    }

    /**
     * 智能派单
     *
     * @param assigner 注意参数一个json对象字符串
     * @return
     */
    @PostMapping("assigner")
    public List<Map> assigner(@MultiRequestBody String assigner) {
//        String url = baseUrl+"/openapi/yuqing/icp/v1/chengdu/assigner";
        String url = "http://10.1.227.188:8752/v1/chengdu/assigner";
        JSONObject js = JSONObject.parseObject(postCommon(assigner, url));
        List<Map> list = new ArrayList<>();
        if(!Objects.isNull(js)){
            JSONArray ja = js.getJSONArray("pred_top");
            for (int i=0;i<ja.size();i++){
                if (ja.getJSONObject(i).getString("pred_label")==null
                        ||ja.getJSONObject(i).getString("pred_label").equals("null")
                        ||ja.getJSONObject(i).getString("pred_label").length()==0)
                    continue;
                Map<String,String> map = new HashMap<>();
                if (ja.getJSONObject(i).getString("pred_label").equals("成都市")){
                    list.clear();
                    break;
                }
                map.put("CSValue",i+"");
                map.put("CSText",ja.getJSONObject(i).getString("pred_label"));
                list.add(map);
            }
        }
        return list;
    }


    /**
     * 公共代码抽取
     */
    public Map<String, String> commons() {
        String ak = "a9192d158c8146c39b1e55a4a1ae59fa";
        String sk = "gQgSaxZbZAFhgZfxU1Qrxh5Oi8Iy6OJy";
        Map<String, String> headers = new HashMap<>();
        Map<String, String> paramMap = builderHeader(headers, ak, sk);
        paramMap.put("Content-Type", "application/json");
        paramMap.put("x-bce-request-id", "1");
        return paramMap;
    }

    /**
     * post 请求 通用接口代码抽取
     *
     * @param address
     * @param url
     * @return
     */
    public String postCommon(String address, String url) {
        Map<String, String> paramMap = commons();
        String result = "";
        String hot_word = "";
        try {
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            httpPost.addHeader("authorization", paramMap.get("authorization"));
            httpPost.addHeader("date", paramMap.get("date"));
            //工单分类 参数
            httpPost.addHeader("Content-Type", "application/json");
            //这里需要指定请求参数的编码，否则默认是ISO_8859_1
            StringEntity stringEntity = new StringEntity(address, "UTF-8");
            stringEntity.setContentType("application/json");
            stringEntity.setContentType("application/x-www-form-urlencoded");
            httpPost.setEntity(stringEntity);
            HttpResponse response = httpclient.execute(httpPost);
            if (response != null) {
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    result = EntityUtils.toString(resEntity, "UTF-8");
                    System.out.println(result);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * Get 请求 代码抽取
     *
     * @param url
     * @return
     */
    public String getCommon(String url) {
        Map<String, String> paramMap = commons();
        String result = "";
        try {
            HttpClient httpclient = new DefaultHttpClient();
            HttpGet httpGet = new HttpGet(url);
            httpGet.addHeader("authorization", paramMap.get("authorization"));
            httpGet.addHeader("date", paramMap.get("date"));
            httpGet.addHeader("Content-Type", "application/json");
            httpGet.addHeader("x-bce-request-id", "1");
            HttpResponse response = httpclient.execute(httpGet);
            if (response != null) {
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    result = EntityUtils.toString(resEntity, "UTF-8");
                    System.out.println(result);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 类案推荐
     * @param title
     * @param content
     * @return
     */
    @PostMapping("recommend")
    public String recommend(String title,String content) {
//        String url = baseUrl+"/openapi/v1/event/analysis/part3/sim_order_searcher_server";
        String url = "http://10.1.227.188:8752/v1/sim_order_searcher_server";
        if (title==null) title="";
        String body = "{\"title\": \""+title+"\",\n" +
                "\"content\": \""+content+"\",\n" +
                "\"sort_filed\": \"sim_score\"}";
        return postRequest(body,url);
    }

    /**
     * 被诉主体
     *  抽取工单中的要素
     * @param content 注意参数为普通字符串
     * @return
     */
    @PostMapping("argument")
    public String argument(@MultiRequestBody String content) {
//        String url = baseUrl+"/openapi/v1/event/analysis/part1/argument";
        String url = "http://10.1.227.188:8752/argument";
        String body = "{" +
                "\"requestId\": \"123\"," +
                "\"workOrders\": ["+
                "{\"title\": \"\", \"content\": \""+content+"\"}]}";
        return postRequest(body,url);
    }

    /**
     * 同号工单来电
     * @param phone
     * @return
     */
    @PostMapping("workList")
    @ResponseBody
    public  Object workList(String phone) {
        System.out.println(phone);
//        String url = baseUrl+"/v2/order_event_search/common_work_order_chengdu_online_v2/event_analysis_rank_search";
        String url = "http://10.1.227.188:8092/v2/order_event_search/common_work_order_chengdu_online_v2/event_analysis_rank_search";
        String body = "{" +
                      "    \"publisherPhone\": [\""+phone+"\"]" +
                       "}";
        JSONObject jsonObject = JSONObject.parseObject(postRequest(body,url));
        System.out.println(jsonObject);
        JSONArray jsonArray = jsonObject.getJSONArray("WorkOrderEvent");
        JSONObject res = new JSONObject();
        List<String> id = new ArrayList<>();
        for(int i=0;i<jsonArray.size();i++){
            id.add(jsonArray.getJSONObject(i).getString("id"));
        }
        res.put("eventId",id);
        res.put("publisherPhone",new String[]{phone});
        System.out.println(res.toJSONString());
//        JSONObject json =  JSONObject.parseObject(postRequest(res.toJSONString(),baseUrl+"/v2/order_event_search/common_work_order_chengdu_online_v2/order"));
        JSONObject json = JSONObject.parseObject(postRequest(res.toJSONString(),"http://10.1.227.188:8092/v2/order_event_search/common_work_order_chengdu_online_v2/order"));
        return json;
    }

    public String  postRequest(String body,String url){
        String ak = "a9192d158c8146c39b1e55a4a1ae59fa";
        String sk = "gQgSaxZbZAFhgZfxU1Qrxh5Oi8Iy6OJy";

        Map<String, String> headers = new HashMap<>();
        Map<String, String> paramMap = AuthUtil.builderHeader(headers, ak, sk);
        paramMap.put("Content-Type", "application/json");
        paramMap.put("x-bce-request-id", "123456");

        String result = "";
        try {

            HttpClient httpclient = new DefaultHttpClient();
            // HttpGet httpGet = new HttpGet(url);
            //添加header参数

            HttpPost httpPost = new HttpPost(url);
            httpPost.addHeader("authorization", paramMap.get("authorization"));
            httpPost.addHeader("date", paramMap.get("date"));
            // httpPost.addHeader("authorization","hmac username=\"a9192d158c8146c39b1e55a4a1ae59fa\", algorithm=\"hmac-sha256\", headers=\"date\", signature=\"jAoMOSdbRCOrTfQsWPqUFHEbKnw5ZsU7Lmyz9pGv3vw=\"");
            // httpPost.addHeader("date", "Fri, 08 Apr 2022 09:11:31 GMT");
            httpPost.addHeader("Content-Type", "application/json");
            httpPost.addHeader("x-bce-request-id", "123456");
            //这里需要指定请求参数的编码，否则默认是ISO_8859_1
            StringEntity stringEntity = new StringEntity(body,"UTF-8");
            stringEntity.setContentType("application/json");
            httpPost.setEntity(stringEntity);
            HttpResponse response = httpclient.execute(httpPost);
            if(response != null){
                HttpEntity resEntity = response.getEntity();
                if(resEntity != null){
                    result = EntityUtils.toString(resEntity,"UTF-8");
                    //System.out.println(result);
                }
            }
        }catch (Exception e){
            e.printStackTrace();

        }
        return result;
    }

    /**
     * 类案推荐
     */
    @PostMapping("/caseRecommend")
    public AjaxResult caseRecommend(@MultiRequestBody String params){
        return AjaxResult.success(JSONObject.parseObject(baiduApi.caseRecommend(params)));
    }

    /**
     * 关键词提取
     */
    @PostMapping("/getHotWord")
    public AjaxResult getHotWord(@MultiRequestBody String params){
        return AjaxResult.success(JSONObject.parseObject(baiduApi.getHotWord(params)));
    }

    /**
     * 智能纠错
     */
    @PostMapping("/errorCorrection")
    public AjaxResult errorCorrection(@MultiRequestBody String params){
        return AjaxResult.success(JSONObject.parseObject(baiduApi.errorCorrection(params)));
    }

    /**
     * 承办单位内荐
     */
    @PostMapping("/handleDeptRecommend")
    public AjaxResult handleDeptRecommend(@MultiRequestBody String params){
        return AjaxResult.success(JSONObject.parseObject(baiduApi.handleDeptRecommend(params)));
    }

    /**
     * 内容类别推荐
     */
    @PostMapping("/contentTypeRecommend")
    public AjaxResult contentTypeRecommend(@MultiRequestBody String params){
        return AjaxResult.success(JSONObject.parseObject(baiduApi.contentTypeRecommend(params)));
    }

    /**
     * 地址查询
     * @param address
     * @return
     */
    @GetMapping("/addressSearch")
    public AjaxResult addressSearch(@RequestParam String address){
        if (address == null){
            return AjaxResult.success();
        }
        String url  = "&queryType=placepoi&pageNum=1&pageSize=10&q=" + address;
        return AjaxResult.success(JSONObject.parseObject(baiduApi.addressSearch(url)));
    }

    /**
     * 查询部门编号
     * @param deptName
     * @return
     */
    @PostMapping("/selectRecommendDeptNo")
    public AjaxResult selectRecommendDeptNo(String deptName){
        String deptNo = commonServiceImpl.selectDeptShort(deptName);
        if (deptNo != null){
            return AjaxResult.success("插叙成功",deptNo);
        }else{
            return AjaxResult.error("部门不存在！");
        }
    }

    @PostMapping("/selectContentTypeNo")
    public AjaxResult selectContentTypeNo(String types){
        String[] typeList = types.split("-");
        int nums = typeList.length, level = nums;
        BSort bSort = new BSort();
        if (nums > 0){
            // 查询最后一个唯一：返回
            List<BSort> bSortList = new ArrayList<>();
            for (int i = nums -1; i >= 0 ; i--,level--) {
                bSortList = commonService.findBSortNoByName(typeList[i],level);
                if (bSortList.size() == 1){
                    bSort = bSortList.get(0);
                    break;
                }
            }
            if (bSort.getSortname().equals(typeList[nums-1]) && level == nums) {
                return AjaxResult.success("查询成功",bSort);
            } else {
                for (int i = level; i < nums; i++) {
                    BSort nextBSort = commonService.selectBSortNoByParent(typeList[level], bSort.getCodepk());
                    if (nextBSort.getSortname().equals(typeList[nums-1]) && nums == nextBSort.getLayernum()){
                        bSort = nextBSort;
                        break;
                    }
                    bSort = nextBSort;
                }
                return AjaxResult.success("查询成功",bSort);
            }
        }
        return AjaxResult.error("查询失败！");
    }
}
